
#include "cgpssim.h"

#include <QDataStream>
#include <QTcpSocket>
#include <iostream>
CGPSSim::CGPSSim(QObject *parent)
{
}

CGPSSim::~CGPSSim()
{
}


void CGPSSim::prepareWriteData(QByteArray* block, void* param)
{
    // we cannot discrete this definition to the outside of the block,
    // and pass the reference to the funtion, or it will cause some
    // unknown problems, such as wrong streams. Maybe it is a bug of QT.
    QDataStream out(block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_3);


    protocal::ClientPos* pClientPos = (protocal::ClientPos*)param;
    pClientPos->source = protocal::CAR;
    pClientPos->car_command = protocal::CAR_CARPOS;
    pClientPos->size = sizeof(protocal::ClientPos);

    // output the head information
    out << (qint32)(pClientPos->source) \
        << (qint32)(pClientPos->cli_command) \
        << (qint32)(pClientPos->size);

    // output the body information

    //
    char * temp = new char [10];
    // we must do so, because the constructor of QString(char*) will truncate the
    // remaining space after '\0', and we need them to occupy the space.
    memcpy(temp, pClientPos->Order_ID, 10);
    out << temp;
    qDebug(temp);
    delete [] temp;
    short align = 9;
    out << align;
    out << pClientPos->Current_Gps.lat << pClientPos->Current_Gps.lon << pClientPos->Current_Gps.time;
    std::cout << "TaxiSend:" << pClientPos->source << std::endl;



}

bool CGPSSim::prepareReadData(QTcpSocket *pTcpSocket, protocal::BasePtc *basePtc)
{
    QDataStream in(pTcpSocket);

    if (   basePtc->source != protocal::SERVER\
        || basePtc->srv_command != protocal::SRV_CLIENTPOS\
        || basePtc->size != sizeof(protocal::SrvToCliPos))
    {
        // TODO: check whether it is necessary to clear the contents of in or pTcpSocket.
        // make an experiment to verify it.
        return false;
    }
    unsigned int temp;
    //short align;
    //in >> align;
    in >> this->lat >> this->lon >> temp;

    this->formResult();

    std::cout << "TaxiRecv:" << basePtc->source << std::endl;

    return true;
}

void CGPSSim::formResult()
{
    resultMap.insert(QString("lat"), QString::number((unsigned)lat));
    resultMap.insert(QString("lon"), QString::number((unsigned)lon));
}
